﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;
using System.Windows;

namespace TreeBuilder
{
	public class ActionHistory
	{
		private readonly Stack<UndoableAction> _undoStack = new Stack<UndoableAction>();
		private readonly Stack<UndoableAction> _redoStack = new Stack<UndoableAction>();

		public event Action ExecutingAction;

		protected virtual void OnExecutingAction()
		{
			Action handler = ExecutingAction;
			if (handler != null) handler();
		}

		public void ExecuteAction(UndoableAction action)
		{
			action.Execute();
			_undoStack.Push(action);
			_redoStack.Clear();
			OnExecutingAction();
		}

		public bool CanUndo
		{
			get { return _undoStack.Count > 0; }
		}

		public void Undo()
		{
			if (!CanUndo)
				throw new InvalidOperationException("Cannot undo: undo stack is empty");
			var action = _undoStack.Pop();
			action.Undo();
			_redoStack.Push(action);
		}

		public bool CanRedo
		{
			get { return _redoStack.Count > 0; }
		}

		public void Redo()
		{
			if (!CanRedo)
				throw new InvalidOperationException("Cannot redo: redo stack is empty");
			var action = _redoStack.Pop();
			action.Execute();
			_undoStack.Push(action);
		}
	}
}